import { useState, forwardRef, useImperativeHandle } from 'react';
import {
  StyleSheet,
  View,
  Text,
  Modal,
  Image,
  TouchableOpacity,
  TextInput,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import { getUUID } from '../utils/uuid';
import { setStorage, getStorage, removeStorage } from '../utils/storage';
import icon_close_modal from '../assets/icon_close_modal.png';
const AddCount = forwardRef((props: any, ref) => {
  // console.log('AddCount', props);
  const [visible, setVisible] = useState(false);
  const [activeIndex, setActiveIndex] = useState(0);
  const [id, setId] = useState('');
  const [name, setName] = useState('');
  const [count, setCount] = useState('');
  const [password, setPassword] = useState('');
  const [isEdit, setIsEdit] = useState(false);
  const show = async (data: any) => {
    // await removeStorage('countList');
    if(data && data.id){
      const index = props.types.findIndex((item: string) => item === data.type);
      setActiveIndex(index);
      setId(data.id);
      setName(data.name);
      setCount(data.count);
      setPassword(data.password);
      setIsEdit(true);
    }else{
      setActiveIndex(0);
      setId('');
      setName('');
      setCount('804848200');
      setPassword('123456');
      setIsEdit(false);
    }
    setVisible(true);
  };
  const hide = () => setVisible(false);
  useImperativeHandle(ref, () => ({
    show,
    hide,
  }));
  const renderTitle = () => {
    const styles = StyleSheet.create({
      titleCon: {
        width: '100%',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
      },
      titleTxt: {
        fontSize: 16,
        fontWeight: '500',
        color: '#333',
      },
      closeBtn: {
        position: 'absolute',
        right: 6,
      },
      closeIcon: {
        width: 20,
        height: 20,
        resizeMode: 'contain',
        tintColor: '#999',
      },
    });
    return (
      <View style={styles.titleCon}>
        <Text style={styles.titleTxt}>{isEdit ? '编辑账号' : '添加账号'}</Text>
        <TouchableOpacity
          style={styles.closeBtn}
          activeOpacity={0.7}
          onPress={hide}
        >
          <Image source={icon_close_modal} style={styles.closeIcon} />
        </TouchableOpacity>
      </View>
    );
  };
  const renderTypes = () => {
    const styles = StyleSheet.create({
      typesCon: {
        width: '100%',
        height: 32,
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 8,
      },
      tab: {
        flex: 1,
        height: '100%',
        alignItems: 'center',
        justifyContent: 'center',
        borderColor: '#c0c0c0',
        borderWidth: 0.5,
        borderRightWidth: 0,
        marginLeft: -0.5,
      },
      tabFirst: {
        borderTopLeftRadius: 8,
        borderBottomLeftRadius: 8,
      },
      tabLast: {
        borderTopRightRadius: 8,
        borderBottomRightRadius: 8,
        borderRightWidth: 0.5,
      },
      tabActive: {
        backgroundColor: '#3050ff',
        borderColor: '#3050ff',
      },
      tabTxt: {
        fontSize: 14,
        color: '#333',
      },
      tabTxtActive: {
        color: '#fff',
      },
    });
    const tabClick = (index: number) => {
      if(index === activeIndex || isEdit) return; 
      setActiveIndex(index);
    };
    return (
      <View style={styles.typesCon}>
        {props.types.map((item, index) => (
          <TouchableOpacity
            style={[
              styles.tab,
              index === 0 && styles.tabFirst,
              index === props.types.length - 1 && styles.tabLast,
              index === activeIndex && styles.tabActive,
            ]}
            key={index}
            activeOpacity={0.7}
            onPress={() => tabClick(index)}
          >
            <Text
              style={[
                styles.tabTxt,
                index === activeIndex && styles.tabTxtActive,
              ]}
            >
              {item}
            </Text>
          </TouchableOpacity>
        ))}
      </View>
    );
  };
  const renderFieldInput = (
    label: string,
    value: string,
    setValue: (text: string) => void,
    maxLength: number = 10,
  ) => {
    const styles = StyleSheet.create({
      subTitleTxt: {
        fontSize: 12,
        color: '#666',
        marginTop: 16,
      },
      input: {
        width: '100%',
        height: 40,
        backgroundColor: '#f0f0f0',
        marginTop: 8,
        borderRadius: 8,
        paddingHorizontal: 12,
        fontSize: 14,
        color: '#333',
      },
    });
    return (
      <>
        <Text style={styles.subTitleTxt}>{label}</Text>
        <TextInput
          style={styles.input}
          maxLength={maxLength}
          placeholder={`请输入${label}`}
          placeholderTextColor="#999"
          value={value}
          onChangeText={setValue}
          keyboardType={label === '密码' ? 'visible-password' : 'default'}
        />
      </>
    );
  };

  const submit = async () => {
    const newCount = {
      id: isEdit ? id : getUUID(),
      name,
      count,
      password,
      type: props.types[activeIndex],
    };
    const countList = (await getStorage('countList')) || [];
    if (isEdit) {
      const index = countList.findIndex((item: any) => item.id === id);
      countList.splice(index, 1, newCount); // 替换
    } else {
      countList.push(newCount);
    }
    await setStorage('countList', countList);
    props.onSave && props.onSave();
    hide();
  };
  return (
    <Modal
      animationType="fade"
      transparent={true}
      visible={visible}
      onRequestClose={hide}
      statusBarTranslucent={true}
    >
      <KeyboardAvoidingView
        style={styles.root}
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      >
        <View style={styles.content}>
          {renderTitle()}
          <Text style={styles.subTitleTxt}>账号类型</Text>
          {renderTypes()}
          {renderFieldInput('账号名', name, setName)}
          {renderFieldInput('账号', count, setCount, 20)}
          {renderFieldInput('密码', password, setPassword, 6)}
          <TouchableOpacity
            style={styles.submitBtn}
            activeOpacity={0.7}
            onPress={submit}
          >
            <Text style={styles.submitBtnTxt}>保 存</Text>
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    </Modal>
  );
});

const styles = StyleSheet.create({
  root: {
    width: '100%',
    height: '100%',
    backgroundColor: '#00000060',
    justifyContent: 'center',
    alignItems: 'center',
  },
  content: {
    width: '80%',
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 12,
  },
  subTitleTxt: {
    fontSize: 12,
    color: '#666',
    marginTop: 16,
  },
  submitBtn: {
    width: '100%',
    height: 40,
    backgroundColor: '#3050ff',
    borderRadius: 8,
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 20,
  },
  submitBtnTxt: {
    fontSize: 14,
    color: '#fff',
  },
});

export default AddCount;
